﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace OAuthApp.Services
{
    public class ApiRequestLoggingAttribute : IActionFilter
    {
        readonly IWebHostEnvironment _webHostEnvironment;
        readonly ILogger<ApiRequestLoggingAttribute> _logger;

        public ApiRequestLoggingAttribute(
            ILogger<ApiRequestLoggingAttribute> logger
            , IWebHostEnvironment webHostEnvironment)
        {
            _logger = logger;
            _webHostEnvironment = webHostEnvironment;
        }

        public ApiRequestLoggingAttribute()
        {

        }

        IDictionary<string, object> args { get; set; }

        IHeaderDictionary headers { get; set; }

        string path { get; set; }

        string time { get; set; }

        object result { get; set; }

        string time_e { get; set; }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (!AppConst.UseNLog) { return; }

            if (context.Result is ObjectResult)
            {
                result = (context.Result as ObjectResult).Value;
            }
            else if (context.Result is JsonResult)
            {
                result = (context.Result as JsonResult).Value;
            }

            time_e = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fffffff");

            var log = JsonConvert.SerializeObject(new
            {
                time,
                time_e,
                path,
                args,
                result,
                headers,
            });

            _logger.LogInformation(log);
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!AppConst.UseNLog) { return; }

            time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fffffff");

            path = context.HttpContext.Request.Path;

            args = context.ActionArguments;

            headers = context.HttpContext.Request.Headers;
        }
    }
}
